package com.googlecode.flealancemarket.tapestry.util;

import java.util.List;

import org.apache.tapestry.ValueEncoder;
/**
 * General purpose value encoder for domain classes implemented as JavaBeans
 * It needs a reference to a List containing all available instances of its type - allBeans,
 * and a String which represents the property (through getter), 
 * which is unique for its instances - propertySelector
 * 
 * Beans MUST override toString() and return value of that property
 * 
 * @author Goran Jovic <goranjovic@gmail.com/>
 * @since Sep 16, 2008
 **/
public class BeanEncoder<T> implements ValueEncoder<Object>{

	
	private String propertySelector;
	private List<T> allBeans;

	public BeanEncoder(String propertySelector, List<T> allBeans) {
		this.propertySelector = propertySelector;
		this.allBeans = allBeans;
	}

	@SuppressWarnings("unchecked")
	public String toClient(Object object) {
		T bean = (T) object;
		return bean.toString();
	}

	public Object toValue(String propertyValue) {
		UniversalFinder finder = new UniversalFinder();
		T bean = finder.find(allBeans, propertySelector, propertyValue);
		return bean;
	}

}
